package sample.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

public class TencentUtils {

    private static final String domain = "https://apis.map.qq.com";
    private static final String searchUrl = "/ws/place/v1/search";
    private static final String sk = "L3d8fTNe1a0p1rLHixLwiOa8cyxzmjxU";
    private static final String key = "SOLBZ-ZLPC4-LA3UM-DT4WE-5EO4K-6LBWE";


    public static String getUrl(String keyword, String area, Integer pageSize, Integer pageNo){
        Map<String, Object> paramMap = new TreeMap<>();
        paramMap.put("keyword", keyword);
        paramMap.put("boundary", "region("+area+",0)");
        paramMap.put("page_size", pageSize);
        paramMap.put("page_index", pageNo);
        paramMap.put("output", "json");
        paramMap.put("orderby", "_distance");
        paramMap.put("key", key);
        List<Map.Entry<String, Object>> list = new ArrayList<Map.Entry<String, Object>>(paramMap.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Object>>() {
            public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
                return o1.getKey().compareTo(o2.getKey());
            }
        });


        String params = list.stream().map(x->x.getKey()+"="+x.getValue()).collect(Collectors.joining("&"));
        String sig = Md5Utils.md5(searchUrl+"?"+params+sk);


        try {
            paramMap.put("boundary", URLEncoder.encode(paramMap.get("boundary").toString(),"utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        list = new ArrayList<Map.Entry<String, Object>>(paramMap.entrySet());
        String finalPparams = list.stream().map(x->x.getKey()+"="+x.getValue()).collect(Collectors.joining("&"));

        return domain+searchUrl+"?"+ finalPparams+"&sig="+sig;

    }

    public static void main(String[] args) {
        String url = "https://apis.map.qq.com/ws/place/v1/search?boundary=region({region},0)&key=SOLBZ-ZLPC4-LA3UM-DT4WE-5EO4K-6LBWE&keyword={keyword}&orderby=_distance&output=json&page_index={page_index}&page_size={page_size}&sig={sig}";
        url = url.replace("{region}", "北京").replace("{keyword}", "减肥").replace("{page_index}", "1").replace("{page_size}", "1");
        String sig = Md5Utils.md5(url.replace("&sig={sig}", ""));
        url = url.replace("{sig}", sig).replace("region(北京,0)", URLEncoder.encode("region(北京,0)"));
        System.out.println(url);

        System.out.println(getUrl("减肥","北京",1,1));
        //System.out.println(Md5Utils.md5("/ws/geocoder/v1?key=5Q5BZ-5EVWJ-SN5F3-*****&location=28.7033487,115.8660847SWvT26ypwq5Nwb5RvS8cLi6NSoH8HlJX"));
    }
}
